package yanc.app

import grails.converters.JSON
import grails.transaction.Transactional
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value

import javax.imageio.ImageIO

class UserController {
    @Value('${appInterceptor.verifyUrl}')
    protected String VERIFYURL

    @Value('${appInterceptor.url}')
    protected String URL
    def userService
    static final Logger logger = LoggerFactory.getLogger(UserController.class)

    def vali() {
        def data = [:]
        println "vali"
        def username = "${params.username}"
        def password = "${params.password}"
        try {
            User user = User.findByAccountAndPassword(username, userService.getMD5(password))
            if (user == null) {
                def u = User.findByAccount(username)
                if (u) {
                    u.times = u.times + 1
                    userService.add(u)
                    if (u.times > 2) {
                        data << [statuCode: "1", errMsg: "1", codeState: "0"]
                    } else {
                        data << [statuCode: "1", errMsg: "1", codeState: "1"]
                    }
                } else {
                    data << [statuCode: "1", errMsg: "1", codeState: "1"]
                }
            } else {
                if (user.state == true) {
                    session.user = user.account
                    session.setMaxInactiveInterval(60 * 60 * 2)
                    if (user.times < 3) {
                        user.times = 0
                        userService.add(user)
                        data << [statuCode: "0", errMsg: "0", codeState: "1", data: user.account]
                    } else {
                        user.times = 0
                        userService.add(user)
                        data << [statuCode: "0", errMsg: "0", codeState: "0", data: user.account]
                    }
                } else {
                    data << [statuCode: "1", errMsg: "1", codeState: "1"]
                }
            }
            render data as JSON
        } catch (Exception e) {
            logger.error("UserController -- vali Exception " + e.message)
        }
    }

    @Transactional
    def refresh() {
        def data = [:]
        def username = "${params.account}"
        def oldPassword = "${params.oldPassword}"
        def newPassword = "${params.newPassword}"
        try {
            def user = User.findByAccountAndPassword(username, userService.getMD5(oldPassword))
            if (user) {
                user.password = userService.getMD5(newPassword)
                user.save()
                data << [statuCode: "0", errMsg: "0"]
                render data as JSON
            } else {
                data << [statuCode: "1", errMsg: "1"]
                render data as JSON
            }
        } catch (Exception e) {
            logger.error("UserController -- refresh Exception " + e.message)
        }
    }

    def getAll() {
        def data = [:]
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        def account = "${params.acc ?: ''}"
        try {
            def a = User.createCriteria()
            def list = a.list(max: pagesize, offset: (page - 1) * pagesize) {
                and {
                    if (!account.isEmpty()) {
                        eq("account", account)
                    }
                    not { 'in'("account", ['Superadmin']) }
                }
            }
            def b = User.createCriteria()
            def total = b.get {
                and {
                    if (!account.isEmpty()) {
                        eq("account", account)
                    }
                    not { 'in'("account", ['Superadmin']) }
                }
                projections {
                    count("account")
                }
            }
            if (list) {
                data << [statuCode: "0", errMsg: "0", data: list, total: total]
            } else {
                data << [statuCode: "1", errMsg: "1"]
            }
            render data as JSON
        } catch (Exception e) {
            logger.error("UserController -- getAll Exception " + e.message)
        }
    }

    def getOne() {
        def data = [:]
        def account = "${params.account ?: ''}"
        try {
            def user = User.findByAccount(account)
            data << [statuCode: "0", errMsg: "0", data: user]
            render data as JSON
        } catch (Exception e) {
            logger.error("UserController -- getOne Exception " + e.message)
        }
    }

    def saves() {
        def data = [:]
        def account = "${params.account ?: ''}"
        def user = User.findByAccount(account)
        bindData(user, params, [exclude: ['account']])
        try {
            userService.add(user)
            data << [statuCode: "0", errMsg: "0"]
            render data as JSON
        } catch (Exception e) {
            logger.error("UserController -- saves Exception " + e.message)
        }
    }

    def sa() {
        def data = [:]
        def account = "${params.account ?: ''}"
        def state = "${params.state ?: ''}"
        try {
            def user = User.findByAccount(account)
            if (state == 'true') {
                user.state = true
            } else {
                user.state = false
            }
            userService.add(user)
            data << [statuCode: "0", errMsg: "0"]
            render data as JSON
        } catch (Exception e) {
            logger.error("UserController -- sa Exception " + e.message)
        }
    }

    def update() {
        def data = [:]
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        def account = "${params.account ?: ''}"
        def roleId = "${params.roleId ?: ''}"
        println account
        try {
            def user = User.findByAccount(account)
            user.rolesId = roleId
            userService.add(user)
            def a = User.createCriteria()
            def list = a.list(max: pagesize, offset: (page - 1) * pagesize) {
                and {
                    not { 'in'("account", ['Superadmin']) }
                }
            }
            def total = User.count() - 1
            data << [statuCode: "0", errMsg: "0", data: list, total: total]
            render data as JSON
        } catch (Exception e) {
            logger.error("UserController -- add Exception" + e.message)
        }
    }

    def loginout() {
        def data = [:]
        try {
            session.invalidate()
            data << [statuCode: "0", errMsg: "0"]
            render data as JSON
        } catch (Exception e) {
            logger.error("UserController -- loginout Exception " + e.message)
        }
    }

    def getCode() {
//        def data = [:]
        response.setHeader("Expires", "-1")
        response.setHeader("Cache-Control", "no-cache")
        response.setHeader("Pragma", "-1")
        userService.get()
        session.setAttribute("seesionCode", userService.getStr())
        println userService.getStr()
        ImageIO.write(userService.getImage(), "jpg", response.getOutputStream())
    }

    def checkCode() {
        def data = [:]
        def code = "${params.code ?: ''}"
        def sessionCode = session.getAttribute("seesionCode")
        def str = userService.checkCode(sessionCode, code)
        data << [statuCode: "0", errMsg: "0", data: str]
        render data as JSON
    }

    def auth() {
        def data = [:]
        def token = "${params.token}"
        println "session.isLogin: ${session.isLogin}"
        // 已经登录，放行
//        if (session.isLogin) {
//            true
//        } else {
        // 从认证中心回跳的带有token的请求，有效则放行
//            def token = request.getParameter("token")
        println token
        if (token) {
            // 校验token
            def username = HTTPUtil.verifyToken(VERIFYURL, token)
            // 如果用户名为空说明校验失败

            if (!username) {
                data << [code: "1"]
            } else {
//                    session.isLogin = true
                session.token = token
//                    ap
                println "登录返回成功"
                println session.id
                println "id"
                session.user = username
                session.setMaxInactiveInterval(60 * 60 * 2)
                data << [code: "0", username: username]
            }
        } else {
//                redirect(url: "${URL}/login?service=${request.getRequestURL()}")
//                false
            data << [code: "2"]
        }
//        }
        response.setHeader("Access-Control-Allow-Origin", "*")
        //告诉浏览器编码方式
        response.setHeader("Content-Type", "text/html;charset=UTF-8")
        render data as JSON


    }
    /**
     * 同步用户/更新用户
     */
    def syncuser() {
        def data = [:]
        def username = "${params.username}"
        def name = "${params.name}"
        def telephone = "${params.mobile}"
        def gender = "${params.gender}"
        def address = "${params.address}"
        def age = "${params.age}"
        def state = "${params.flag}"

        def users = User.findByAccount(username)
        if (users) {
            userService.updateUser(telephone, gender, age, address, users, name)
            data << [code: "0", description: "已同步成功"]
        } else {
            println "2"
            def user = new User(account: username)
            user.userId = new Date().format("ddHHmmss")
            user.age = age
            user.gender = gender
            user.address = address
            user.name = name
            user.telephone = telephone
            user.password = ""
            if (state == "0") {
                user.rolesId = 1
            } else {
                user.rolesId = ""
            }
//            userService.updateUser(telephone, gender, age, address, user, name)
//            def length = User.count()
            def flag = userService.add(user)
            if (flag) {
                data << [code: "0", description: "同步成功"]
            } else {
                data << [code: "1", description: "同步失败"]
            }
        }
        render data as JSON
    }

//yanc
    @Transactional
    def deluser() {
        def data = [:]
        def account = "${params.username}"
        def user = User.findByAccount(account)
        if (user) {
            user.delete()
            data << [code: 0, description: "删除成功"]
        } else {
            data << [code: 0, description: "删除失败，子系统没有该用户"]
        }
        render data as JSON
    }

    //嘉峪关
    @Transactional
    def del() {
        def data = [:]
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        def id = Integer.parseInt("${params.id}")
        def user = User.findById(id)
        user.delete()
        def a = User.createCriteria()
        def list = a.list(max: pagesize, offset: (page - 1) * pagesize) {
            and {
                not { 'in'("account", ['Superadmin']) }
            }
        }
        def total = User.count() - 1
        data << [code: "0", description: "删除成功", data: list, total: total]
        render data as JSON
    }
    def add() {
        def data = [:]
        def page = Integer.parseInt("${params.page ?: 1}")
        def pagesize = Integer.parseInt("${params.pagesize ?: 20}")
        def account = "${params.account ?: ''}"
        try {
            def user = User.findByAccount(account)
            if (user) {
                data << [statuCode: "1", errMsg: "1"]
            } else {
                def users = new User()
                bindData(users, params, [exclude: ['page', 'pagesize']])
                users.state = true
                users.password = userService.getMD5("123456")
                def length = User.count()
                users.userId = length + 1 + ""
                userService.add(users)
                def a = User.createCriteria()
                def list = a.list(max: pagesize, offset: (page - 1) * pagesize) {
                    and {
                        not { 'in'("account", ['Superadmin']) }
                    }
                }
                def total = User.count()-1
                data << [statuCode: "0", errMsg: "0", data: list, total: total]
            }
            render data as JSON
        } catch (Exception e) {
            logger.error("UserController -- add Exception" + e.message)
        }
    }
}
